package cn.wolfcode.wolf2w.redis.service.impl;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfonRedisService;
import cn.wolfcode.wolf2w.redis.util.RedisKeys;
import cn.wolfcode.wolf2w.util.Consts;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserInfonServiceImpl implements IUserInfonRedisService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void setVerifyCode(String phone ,String code) {
        String key = RedisKeys.VERIFY_CODE.join(phone);

        stringRedisTemplate.opsForValue().set(key,code, RedisKeys.VERIFY_CODE.getTime(),TimeUnit.SECONDS);

    }

    @Override
    public String getVerifyCode(String phone) {
        String key = RedisKeys.VERIFY_CODE.join(phone);

        return stringRedisTemplate.opsForValue().get(key);
    }


    @Override
    public String setToken(UserInfo user) {
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        String key =RedisKeys.USER_LOGIN.join(token);
        //把登录用户缓存进redis
        //JSON.toJSONString()对象转json格式的数据
        stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(user),RedisKeys.USER_LOGIN.getTime(),TimeUnit.SECONDS);
        return token;
    }


    @Override
    public UserInfo getUserByTohen(String tohen) {
        if (!StringUtils.hasLength(tohen)){
            return null;
        }
        String key = RedisKeys.USER_LOGIN.join(tohen);
       if (stringRedisTemplate.hasKey(key)){
           String userStr = stringRedisTemplate.opsForValue().get(key);
           //JSON格式转成json对象
           UserInfo userInfo = JSON.parseObject(userStr, UserInfo.class);
           //时间重置
           stringRedisTemplate.expire(key,RedisKeys.USER_LOGIN.getTime(),TimeUnit.SECONDS);
           return  userInfo;
       }

        return null;
    }
}































